/* Copyright (c) 2016-2020 Enfry Ltd. All Rights Reserved.
 * 
 * This software is the confidential and proprietary information of Enfry. 
 * You shall not disclose such Confidential Information
 * and shall use it only in accordance with the terms of the agreements
 * you entered into with Enfry.
 */
package com.jweb.framework.mybatis;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.TypeHandler;

public class BooleanTypeHandler implements TypeHandler<Object> {

    private static final int TRUE = 1;
    private static final int FALSE = 0;

    @Override
    public Boolean getResult(ResultSet rs, String columnName) throws SQLException {
        int value = rs.getInt(columnName);  
        
        if (FALSE == value) {  
            return Boolean.FALSE;  
        } else {  
            return Boolean.TRUE;  
        }
    }

    @Override
    public Boolean getResult(ResultSet rs, int columnIndex) throws SQLException {
        int value = rs.getInt(columnIndex);  
        
        if (FALSE == value) {  
            return Boolean.FALSE;  
        } else {  
            return Boolean.TRUE;  
        }
    }

    @Override
    public Boolean getResult(CallableStatement cs, int columnIndex) throws SQLException {
        int value = cs.getInt(columnIndex);  
        
        if (FALSE == value) {  
            return Boolean.FALSE;  
        } else {  
            return Boolean.TRUE;  
        }  
    }

    @Override
    public void setParameter(PreparedStatement ps, int i, Object parameter, JdbcType jdbcType) throws SQLException {
        if(parameter instanceof String) {
            String param = (String) parameter;
            int value = "false".equalsIgnoreCase(param) || "0".equalsIgnoreCase(param) ? FALSE : TRUE;
            ps.setInt(i, value);
        }
        if(parameter instanceof Integer) {
            int param = (int) parameter;
            int value = param == FALSE ? FALSE : TRUE;
            ps.setInt(i, value);
        }
        if(parameter instanceof Boolean) {
            boolean param = (boolean) parameter;
            int value = !param ? FALSE : TRUE;
            ps.setInt(i, value);
        }
    }
	
}
